﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Drawing;
using System.IO;

namespace Caifu.Fx
{
    public class ValidateCodeManager
    {
        private HttpContext Context;

        public ValidateCodeManager(HttpContext context)
        {
            this.Context = context;
        }

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="length">字符长度</param>
        /// <returns>验证码图片流</returns>
        public Byte[] GenerateCode(Int16 length, String key)
        {
            ValidationCode vc = new ValidationCode(length);
            Context.Session[key] = vc.Code;
            Image img = vc.NextImage(true);
            MemoryStream mem = new MemoryStream();
            img.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
            mem.Flush();
            return mem.ToArray();
        }

        /// <summary>
        /// 比对验证码
        /// </summary>
        /// <param name="inputCode">用户输入的验证码信息</param>
        /// <returns></returns>
        public Boolean ValidationCode(String inputCode, String key)
        {
            return Context.Session[key] != null && !String.IsNullOrEmpty(inputCode)
                ? inputCode.Equals(Context.Session[key].ToString()) : false;
        }
    }
}
